﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using CalemShop.Classes;
using System.Media;

namespace CalemShop.Forms
{
    public partial class FrmStaff : FrmBaseDock
    {
        private int lastLoadTabToday = 0;

        private delegate void AddItemToListViewHandler(ListView control, ListViewItem[] items);
        public FrmStaff()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
        }

        public FrmStaff(FrmCalemShop shop) : base(shop)
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
        }

        private void FrmStaff_Load(object sender, EventArgs e)
        {
            LoadStaffWorkingTimeToday();
        }

        public override void FormActived()
        {
            this.ActiveControl = txtStaffId;
        }

        private void LoadStaffWorkingTimeToday()
        {
            listViewStaff.Items.Clear();
            Thread th = new Thread(new ThreadStart(delegate(){
                try
                {
                    ShowWaitingDialog(true, 0);
                    string today = DateTime.Now.ToString("yyyy-MM-dd");
                    DataTable tb = DataManager.GetStaffWorkingTimeToday(today);
                    if (tb != null && tb.Rows.Count > 0)
                    {
                        ListViewItem[] items = new ListViewItem[tb.Rows.Count];
                        int index = 0;
                        foreach (DataRow r in tb.Rows)
                        {
                            decimal workingTime = 0;
                            decimal.TryParse(r["workingTime"].ToString(), out workingTime);
                            workingTime = Math.Round(workingTime / 3600, 1);
                            DateTime startTime = (DateTime)r["startWorkAt"];
                            DateTime endTime = (DateTime)r["stopWorkAt"];
                            ListViewItem item = new ListViewItem(new string[] {
                                r["staffName"].ToString(),startTime.ToString("dd-MM-yyyy HH:mm:ss"),endTime.ToString("dd-MM-yyyy HH:mm:ss"), workingTime.ToString()
                            });

                            items[index++] = item;
                            item.ImageIndex = 0;
                        }

                        AddListViewItems(this.listViewStaff, items);
                    }
                }
                catch (Exception e)
                {
                    Reporter.WriteErrorEx(e);
                }
                finally
                {
                 ShowWaitingDialog(false, 0);
                }
            }));
            th.IsBackground = true;
            th.Start();
        }

        private void LoadStaffWorkingTime()
        {
            listViewHistory.Items.Clear();
            Thread th = new Thread(new ThreadStart(delegate()
            {
                try
                {
                    ShowWaitingDialog(true, 0);
                    string fromDate = dateTimeFrom.Value.ToString("yyyy-MM-dd");
                    string toDate = dateTimeTo.Value.ToString("yyyy-MM-dd");
                    ListViewItem[] items = DataManager.GetStaffWorkingTime(fromDate, toDate);
                    if (items != null)
                    {
                        AddListViewItems(this.listViewHistory, items);
                    }
                    
                }
                catch (Exception e)
                {
                    Reporter.WriteErrorEx(e);
                }
                finally
                {
                    ShowWaitingDialog(false, 0);
                }
            }));
            th.IsBackground = true;
            th.Start();
        }

        private string GetStaffNameBySerial(string serial)
        {
            try
            {
                object co = DataManager.GetStaffSerialMap()[serial];
                if (co != null)
                {
                    return co.ToString();
                }

                return null;
            }
            catch (Exception e)
            {
                return null;
            }
            
        }

        private void btCheckIn_Click(object sender, EventArgs e)
        {
            CheckIn();
        }

        private void CheckIn()
        {
            if(string.IsNullOrEmpty(txtStaffId.Text)) {
                return;
            }

            string serial = txtStaffId.Text.Trim().ToUpper();
            string name = GetStaffNameBySerial(serial);
            if (name != null)
            {
                DataManager.UpdateStaffWorkingTime(name);
                LoadStaffWorkingTimeToday();
                FrmSale.PlayCompleteSound();
            }
        }

        private void ShowWaitingDialog(bool visible, int pecentage)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CalemShop.Forms.FrmCustomerExplorer.ShowAndUpdateProgressWaitingDlg(ShowWaitingDialog), visible, pecentage);

            }
            else
            {
                if (visible)
                {
                    if (pictureBox1.Visible == false)
                    {
                        pictureBox1.Visible = true;
                        int x = (this.Width - pictureBox1.Width) / 2;
                        int y = (this.Height - pictureBox1.Height) / 2;
                        pictureBox1.Location = new Point(x, y);
                        pictureBox1.Refresh();
                    }
                }
                else
                {
                    pictureBox1.Visible = false;
                    pictureBox1.Refresh();
                }
            }
        }

        private void AddListViewItems(ListView control, ListViewItem[] items)
        {
            if (items != null)
            {
                if (control.InvokeRequired)
                {
                    control.Invoke(new AddItemToListViewHandler(AddListViewItems), control, items);
                }
                else
                {
                    control.Items.Clear();
                    control.Items.AddRange(items);
                }
            }
        }

        private void FrmStaff_Resize(object sender, EventArgs e)
        {
            if (pictureBox1.Visible == true)
            {
                int x = (this.Width - pictureBox1.Width) / 2;
                int y = (this.Height - pictureBox1.Height) / 2;
                pictureBox1.Location = new Point(x, y);
                pictureBox1.Refresh();
            }
        }

        private void btReport_Click(object sender, EventArgs e)
        {
            LoadStaffWorkingTime();
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabToday == tabControl1.SelectedTab)
            {
                ActiveControl = txtStaffId;
                if (Environment.TickCount - lastLoadTabToday >= 10000)
                {
                    LoadStaffWorkingTimeToday();
                    lastLoadTabToday = Environment.TickCount;
                }
            }
        }

        private void txtStaffId_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void txtStaffId_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                e.Handled = true;
                CheckIn();
            }
        }
    }
}
